package com.study.interecptor;

import com.alibaba.fastjson.JSON;
import com.study.annotation.bean.AppContext;
import com.study.Util.CommonResponse;
import com.study.common.constants.RedisCache;
import com.study.Util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器
 */
@Slf4j
@Component
public class UrlInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    RedisCache redisCache;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (request.getRequestURI().startsWith("/mini/login")
                || request.getRequestURI().startsWith("/mini/register")) {
            log.info("拦截放过...");
            return true;
        }

        //检查redis中的缓存是否是空token
        String token = request.getHeader("mini-token");
        if (StringUtils.isBlank(token)) {
            log.info("request token is empty,go to login...");
            String message = JSON.toJSONString(CommonResponse.fail(null,"wxLoginNoAuth","未登录"));
            ServletUtil.senderString(HttpServletResponse.SC_NOT_ACCEPTABLE,response,message);
            return false;
        }

        String cacheAppContext = redisCache.getAppContext(token);
        if (StringUtils.isBlank(cacheAppContext)) {
            log.info("cache token is empty,go to login...");
            String message = JSON.toJSONString(CommonResponse.fail(null,"wxLoginNoAuth","已过期"));
            ServletUtil.senderString(HttpServletResponse.SC_NOT_ACCEPTABLE,response,message);
            return false;
        }

        AppContext appContext = JSON.parseObject(cacheAppContext, AppContext.class);
        request.setAttribute(AppContext.UUID,appContext.getUuid());
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        log.info("请求处理之后进行调用的拦截器方法postHandle");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("请求结束之后被调用的拦截器afterCompletion");
    }
}
